<?php
/*
 * Created on 23.10.2007
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
define('MODEL_SESSION_ADD','INSERT INTO `sessions` (`session_id`, `type` ,`ip` ,`user_id` , `date`) VALUES (?, ?, ?, ?, now())');
define('MODEL_SESSION_FIND', 'select * from `sessions` where session_id = ?');

define('MODEL_SESSION_DELETE','DELETE FROM `sessions` WHERE `session_id` = ?');
//define('DELETE_SESSION','DELETE FROM `sessions` WHERE `session_id` = ?');
//define('GET_SESSION', 'select * from `sessions` where session_id = ?');
//define('CHECK_LOGIN','SELECT count(*) from users where user_login = ? and user_password = ?');

class Model_Session extends Models_Base {
	private $session = null;
	
	
	function __construct() {
		parent::__construct();
		
		if(empty($this->session))
			$this->get();
	}
	
	function create($user_id, $type) {

error_log(" UID: $user_id ");
		$sesid = $this->generateSessionId();
		$this->insertRow(MODEL_SESSION_ADD,array($sesid, $type, $_SERVER['REMOTE_ADDR'], $user_id));
		return $sesid;
	}
	
	function get() {
		$SID = ($_COOKIE['SID']) ? ($_COOKIE['SID']) : ($_GET['SID']);
		$this->session = $this->find($SID);
				
		return $this->session;
	}
	
	function find($sesid) {
		return $this->getRow(MODEL_SESSION_FIND,array($sesid));
	}
	
	function user_id() {
		return $this->session->user_id;
	}
	
//	private function checkLogin ($user_name,$password) {
//		$sth = $this->dbh->prepare(CHECK_LOGIN);
//		
//		if(empty($sth))
//			return -1;
//		
//		$sth->execute(array($user_name,md5(md5($password))));
//		$row = $sth->fetch();
//
//		return $row[0] ? 1 : 0; 
//	}
	
	private function generateSessionId() {
		
		$sesid = '';
		$string = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
		
		while(strlen($sesid) < 20) {

			$sesid .= $string[rand(0,62)];
		} 

		return $sesid;
	}
	
//	function deleteSession($SID) {
//		$sth = $this->dbh->prepare(DELETE_SESSION);
//		$sth->execute(array($SID));
//		$this->logged = 0;
//	}

	function delete() {
		
		$this->get();	
		
		error_log("DELETE SESION: ".$this->session->session_id);
		
		$sth = $this->dbh->prepare(MODEL_SESSION_DELETE);
		$sth->execute(array($this->session->session_id));
		$this->logged = 0;
	}
	
	function sessionInfo() {
		return $this->session;
	}
}
?>
